package com.goudan.rabbitmq.listener;

import com.goudan.rabbitmq.constant.QueueDefinition;
import com.goudan.rabbitmq.message.MsgData;
import com.goudan.rabbitmq.model.Order;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 延迟队列消费者
 */
@Slf4j
@Component
public class DirectQueueListener {

    @RabbitListener(queues = {QueueDefinition.LGD_DIRECT_QUEUE})
    public void receiveDelayQueue(Message message, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag,
                                  Channel channel) throws Exception {
        MsgData<Order> msg = new MsgData<>(message.getBody(), Order.class);
        Order order = msg.getData();
        String messageId = message.getMessageProperties().getMessageId();
        log.info("收到直连消息--->当前时间：{},收到队列消息:{},deliveryTag:{},messageId:{}",
                LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")), order, deliveryTag, messageId);
        try {
            // TODO 业务处理--------------开始
            if ("你大爷".equals(order.getOrderName())) {
                Integer err = 1 / 0;
            }
            // TODO 业务处理--------------结束
            // 手动应答消息，成功应答
//            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            log.error("队列消费异常！:{}", e.getMessage());
            // 消费失败，拒绝应答，消息重新入队(消息重新入队，需要开启相应配置)
//        channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
            throw e;
        }

    }

}
